package com.jrx.anytxn.param.controller.product;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.dto.product.InterestTableReq;
import com.jrx.anytxn.param.dto.product.InterestTableRes;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.product.IInterestTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;

/**
 * 利息表
 *
 * @author Yangxin
 * @date 2019/8/2
 */
@Api(tags = "页面利息参数API接口")
@RestController
@RequestMapping(value = "/param/interests")
public class InterestTableController {
    private static final Logger logger = LoggerFactory.getLogger(InterestTableController.class);
    @Autowired
    IInterestTableService iInterestTableService;
    @Autowired
    private InfoService infoService;

    @ApiOperation(value = "根据租户ID和利率表ID查询利息表信息", notes = "根据租户ID和利率表ID查询利息表信息")
    @GetMapping(value = "/{tenantId}/{interestId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true),
            @ApiImplicitParam(name = "interestId", value = "利率表ID", required = true)
    })
    public TxnRespResult<InterestTableRes> getByTenIdAndInterestId(@NotNull @PathVariable String tenantId, @PathVariable String interestId) {
        TxnRespResult<InterestTableRes> result = new TxnRespResult<>();
        InterestTableRes res;
        try {
            res = iInterestTableService.findByTenIdAndInterestId(String.valueOf(infoService.getUser().getProjectId()), interestId);
            if (res.getBaseRate() != null && res.getBaseRate().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setBaseRate(res.getBaseRate().multiply(BigDecimal.valueOf(100)));
            }
            if (res.getBaseRatePercent() != null && res.getBaseRatePercent().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setBaseRatePercent(res.getBaseRatePercent().multiply(BigDecimal.valueOf(100)));
            }
            if (res.getTaxRate() != null && res.getTaxRate().compareTo(BigDecimal.valueOf(0)) != 0) {
                res.setTaxRate(res.getTaxRate().multiply(BigDecimal.valueOf(100)));
            }
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "分页查询利息表信息", notes = "分页查询利息表信息")
    @GetMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", required = true)})
    public TxnRespResult<TxnPage<InterestTableRes>> getAllPage(@PathVariable(value = "pageNum") Integer pageNum, @PathVariable(value = "pageSize") Integer pageSize) {

        TxnRespResult<TxnPage<InterestTableRes>> result = new TxnRespResult<>();
        TxnPage<InterestTableRes> response;
        String tenantId = String.valueOf(infoService.getUser().getProjectId());
        response = iInterestTableService.findAllPageByTenId(pageNum, pageSize, tenantId);
        result.getSuccess(response);

        return result;
    }

    @ApiOperation(value = "查询所有利息表信息", notes = "查询所有利息表信息")
    @GetMapping(value = "/all")
    public TxnRespResult<List<InterestTableRes>> getAll() {
        TxnRespResult<List<InterestTableRes>> result = new TxnRespResult<>();
        List<InterestTableRes> response;
        String tenantId = String.valueOf(infoService.getUser().getProjectId());
        response = iInterestTableService.findAllByTenId(tenantId);
        result.getSuccess(response);
        return result;
    }


    @ApiOperation(value = "新增利息表信息", notes = "新增利息表信息")
    @PostMapping("/")
    public TxnRespResult<InterestTableRes> createInterestTable(@RequestBody InterestTableReq interestTableReq) {
        InterestTableRes res;
        TxnRespResult<InterestTableRes> result = new TxnRespResult<>();
        try {
            interestTableReq.setBaseRatePercent(interestTableReq.getBaseRatePercent());
            interestTableReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            interestTableReq.setUpdateBy(infoService.getUser().getUserName());
            if (interestTableReq.getBaseRate() != null && interestTableReq.getBaseRate().compareTo(BigDecimal.ZERO) != 0) {
                interestTableReq.setBaseRate(interestTableReq.getBaseRate().divide(BigDecimal.valueOf(100)));
            }
            if (interestTableReq.getBaseRatePercent() != null && interestTableReq.getBaseRatePercent().compareTo(BigDecimal.ZERO) != 0) {
                interestTableReq.setBaseRatePercent(interestTableReq.getBaseRatePercent().divide(BigDecimal.valueOf(100)));
            }
            if (interestTableReq.getTaxRate() != null && interestTableReq.getTaxRate().compareTo(BigDecimal.ZERO) != 0) {
                interestTableReq.setTaxRate(interestTableReq.getTaxRate().divide(BigDecimal.valueOf(100)));
            }
            res = iInterestTableService.addInterestTable(interestTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }


    @ApiOperation(value = "编辑利息表信息", notes = "编辑利息表信息")
    @PutMapping("/")
    public TxnRespResult<InterestTableRes> modifyInterestTable(@RequestBody InterestTableReq interestTableReq) {
        TxnRespResult<InterestTableRes> result = new TxnRespResult<>();
        InterestTableRes res;
        try {
            if (interestTableReq.getBaseRate() != null && interestTableReq.getBaseRate().compareTo(BigDecimal.ZERO) != 0) {
                interestTableReq.setBaseRate(interestTableReq.getBaseRate().divide(BigDecimal.valueOf(100)));
            }
            if (interestTableReq.getBaseRatePercent() != null && interestTableReq.getBaseRatePercent().compareTo(BigDecimal.ZERO) != 0) {
                interestTableReq.setBaseRatePercent(interestTableReq.getBaseRatePercent().divide(BigDecimal.valueOf(100)));
            }
            if (interestTableReq.getTaxRate() != null && interestTableReq.getTaxRate().compareTo(BigDecimal.ZERO) != 0) {
                interestTableReq.setTaxRate(interestTableReq.getTaxRate().divide(BigDecimal.valueOf(100)));
            }
            interestTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = iInterestTableService.modifyInterestTable(interestTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }

        return result;
    }

    @ApiOperation(value = "删除利息表信息", notes = "根据id删除利息表信息")
    @DeleteMapping(value = "/{tenantId}/{interestId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantId", value = "租户Id", required = true),
            @ApiImplicitParam(name = "interestId", value = "利率表ID", required = true)
    })
    public TxnRespResult<Boolean> removeByTenIdAndInterestId(@NotNull @PathVariable String tenantId, @PathVariable String interestId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        Boolean flag;
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);

            flag = iInterestTableService.removeByTenIdAndInterestId(String.valueOf(infoService.getUser().getProjectId()), interestId);
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "通过利率ID，及机构获取利率信息", notes = "通过利率ID，及机构获取利率信息")
    @GetMapping(value = "/interestId/{interestId}/orgId/{orgId}")
    public TxnRespResult<InterestTableRes> getByInterestIdAndOrgId(@NotNull @PathVariable String interestId, @NotNull @PathVariable String orgId) {
        TxnRespResult<InterestTableRes> result = new TxnRespResult<>();
        InterestTableRes interestTableRes;
        try {
            String tenantId= String.valueOf(infoService.getUser().getProjectId());
            interestTableRes = iInterestTableService.findByInterestId(interestId, orgId,tenantId);
            result.getSuccess(interestTableRes);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            result.getFail(TxnRespCode.ERROR.getCode(), e.getMessage());
        }
        return result;
    }

}
